/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
// win_console.cpp - cool windows console


#include "..\global.h"
#include "win_console.h"

#include <crtdbg.h>


/*-----------------------------------------------------------------------------
	EXPORT STUFF
-----------------------------------------------------------------------------*/
DLL_EXPORT	IConsole	*CreateConsole(void)
{
	return new EWinConsole();
}


DLL_EXPORT	void	DestroyConsole(IConsole *con)
{
	delete con;
}


/*-----------------------------------------------------------------------------
	style, color font etc.
-----------------------------------------------------------------------------*/

#define WS_WINDOW		WS_CLIPCHILDREN | WS_CLIPSIBLINGS
#define WBORDER			2*GetSystemMetrics(SM_CXFIXEDFRAME)
#define HBORDER			2*GetSystemMetrics(SM_CYFIXEDFRAME)+GetSystemMetrics(SM_CYCAPTION)

#define USE_DEBUG_WINDOW	1

#define CONSOLE_CLASSNAME	"Console Window"
#define CONSOLE_WNDNAME		"Console"

#define SYSCON_TEXTCOLOR	0xFFFFFF	//	New Theme
#define SYSCON_BACKGROUND	0x202020
#define SYSCON_WINDOWCOLOR	0x404040	//*/
														
/*#define SYSCON_FONT			"Lucida Console"
#define SYSCON_FONTWIDTH	0
#define SYSCON_FONTHEIGHT	18*/
#define SYSCON_FONT			"Courier"
#define SYSCON_FONTWIDTH	0
#define SYSCON_FONTHEIGHT	12	//*/
/*#define SYSCON_FONT			"Terminal"
#define SYSCON_FONTWIDTH	8
#define SYSCON_FONTHEIGHT	-12*/


#define	SYSCON_WIDTH		800
#define SYSCON_HEIGHT		500
#define SYSCON_LINEHEIGHT	15
#define SYSCON_SPLIT		1

#define	SYSCON_POS_X		20
#define SYSCON_POS_Y		20


/*-----------------------------------------------------------------------------
	Constructor/Destructor
-----------------------------------------------------------------------------*/

EWinConsole::EWinConsole(void)
{		  
	if (initialized) FATAL("Win32 Console already initialized");

#ifdef USE_DEBUG_WINDOW	
	CreateConsoleWindow();
#endif	
	waiting		=	false;
	initialized	=	true;
}


EWinConsole::~EWinConsole(void)
{
	initialized	=	false;
#ifdef USE_DEBUG_WINDOW	
	DestroyConsoleWindow();
#endif	
}



/*-----------------------------------------------------------------------------
	Stuff
-----------------------------------------------------------------------------*/
vector<string>	console_push;

//
//	XTSystem::ConsoleOutput
//
void EWinConsole::ConsoleOutput(const char *text)
{
	SYSTEMTIME	systime;
	GetSystemTime(&systime);
	
	string uncolored = DecolorizeString(text);

	string	date = va("%02d:%02d:%02d", systime.wHour, systime.wMinute, systime.wSecond);

	#ifdef _DEBUG
		_CrtDbgReport(_CRT_WARN, 0, 0, NULL, va("[%s] %s\r\n", date.c_str(), uncolored.c_str()));
	#endif
	// DHG : How to check editbox overflow?

#ifdef USE_DEBUG_WINDOW	
	console_push.push_back(va("%s\r\n", uncolored.c_str()));
#endif	
	/*SendMessage(hTextBuf, EM_SETSEL, (WPARAM)(65536), (LPARAM)(65536));
	SendMessage(hTextBuf, EM_REPLACESEL, (WPARAM)0, (LPARAM)text);*/

	lines.push_back(string(text));	
}


//
//	EWinConsole::SetInputHandler
//
void EWinConsole::SetInputHandler(IConsoleInputHandler *new_handler)
{
	input_handler	=	new_handler;
}


//
//	EWinConsole::Clear
//
void EWinConsole::Clear(void)
{
}


//
//	EWinConsole::Wait
//
char EWinConsole::Wait(void)
{
	key		=	0;
	waiting	=	true;
	
	Log("\r\n\r\nPress any key to continue...\r\n\r\n");

	MSG	msg;
	while(waiting)
	{
		if ( PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE) ) {
			if ( GetMessage(&msg, 0, 0, 0) ) {
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			} else break;
		} else {	
			Sleep(1);	// DHG : Why "Sleep" was comented?
		}
	}
	return key;
}


//
//	EWinConsole::GetConsoleLine
//
const char *EWinConsole::GetLine(uint line)
{
	if (line>=lines.size()) {
		return NULL;
	}
	return lines[line].c_str();
}


uint EWinConsole::GetLineNum(void)
{
	return (uint)lines.size();
}


/*-----------------------------------------------------------------------------
	Private stuff
-----------------------------------------------------------------------------*/

IConsoleInputHandler	*EWinConsole::input_handler	=	NULL;
bool	EWinConsole::waiting		=	false;
char	EWinConsole::key			=	0;
WNDPROC	EWinConsole::OldCmdLineProc	=	NULL;
WNDPROC	EWinConsole::OldTextBufProc	=	NULL;
HWND	EWinConsole::hCmdLine		=	NULL;
HWND	EWinConsole::hConWnd		=	NULL;
HWND	EWinConsole::hTextBuf		=	NULL;
HANDLE	EWinConsole::hLogFile		=	NULL;
bool	EWinConsole::initialized	=	false;


//
//	EWinConsole::CreateConsoleWindow
//
void EWinConsole::CreateConsoleWindow(void)
{
	HINSTANCE	hInst = GetModuleHandle(NULL);
	WNDCLASSEX	wc;

	memset(&wc, 0, sizeof(wc));
		wc.cbClsExtra		=	0;
		wc.cbSize			= sizeof (WNDCLASSEX);
		wc.lpfnWndProc		= ConWndProc;	
		wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
		wc.hInstance		= hInst;
		wc.hbrBackground	= (HBRUSH)CreateSolidBrush(SYSCON_WINDOWCOLOR);
		wc.hCursor			= LoadCursor(NULL, IDC_ARROW);
		wc.lpszClassName	= CONSOLE_CLASSNAME;

	VERIFY( RegisterClassEx(&wc) ) ;

	RECT r;
	GetWindowRect(0, &r);
	uint x	=	SYSCON_POS_X;
	uint y	=	SYSCON_POS_Y;

	// Main Window :
	hConWnd = CreateWindow(CONSOLE_CLASSNAME, CONSOLE_WNDNAME, 
						WS_WINDOW, 
						x,y, 
						SYSCON_WIDTH+WBORDER, SYSCON_HEIGHT+HBORDER, 
						NULL, NULL, hInst, NULL);
						
	ASSERT ( hConWnd );

	
	ShowWindow(hConWnd, SW_NORMAL);
	SetForegroundWindow(hConWnd);
	SetFocus(hConWnd);
	UpdateWindow(hConWnd);

	// Edit Box :
	hTextBuf = CreateWindow("EDIT", "", 
					WS_WINDOW | ES_MULTILINE | ES_READONLY | WS_CHILD /*| WS_BORDER*/ | WS_VSCROLL| ES_AUTOVSCROLL, 
					SYSCON_SPLIT, SYSCON_SPLIT, 
					SYSCON_WIDTH - SYSCON_SPLIT*2, 
					SYSCON_HEIGHT - SYSCON_SPLIT*3 - SYSCON_LINEHEIGHT,
					hConWnd, NULL, hInst, 0);
	
	ASSERT( hTextBuf );
	
	ShowWindow(hTextBuf, SW_NORMAL);
	SetForegroundWindow(hTextBuf);
	SetFocus(hTextBuf);
	UpdateWindow(hTextBuf);

	// Command Line :
	hCmdLine = CreateWindow("EDIT", "", WS_WINDOW | WS_CHILD /*| WS_BORDER*/, 
						SYSCON_SPLIT, SYSCON_HEIGHT - SYSCON_SPLIT*1 - SYSCON_LINEHEIGHT, 
						SYSCON_WIDTH-SYSCON_SPLIT*2, 
						SYSCON_LINEHEIGHT, 
						hConWnd, NULL, hInst, 0);
	ASSERT( hCmdLine );

	ShowWindow(hCmdLine, SW_NORMAL);
	SetForegroundWindow(hCmdLine);
	SetFocus(hCmdLine);
	UpdateWindow(hCmdLine);

	// Set text limit for con editbox :
	SendMessage(hTextBuf, EM_SETLIMITTEXT, 1024*256, 0);


	// Set font for editors :
	HFONT hFont1 = CreateFont(SYSCON_FONTHEIGHT, SYSCON_FONTWIDTH, 
							0,0, 0, FALSE,FALSE,FALSE, 
							DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, 
							DEFAULT_QUALITY, DEFAULT_PITCH, 
							SYSCON_FONT);
	ASSERT(hFont1);

	SendMessage(hTextBuf, WM_SETFONT, (WPARAM)hFont1, (LPARAM)true);
	SendMessage(hCmdLine, WM_SETFONT, (WPARAM)hFont1, (LPARAM)true);

	// Set NewEditProc() for CmdLine...
	OldCmdLineProc = (WNDPROC)GetWindowLong(hCmdLine, GWL_WNDPROC);
	SetWindowLong(hCmdLine, GWL_WNDPROC, (LONG)NewCmdLineProc);

	OldTextBufProc = (WNDPROC)GetWindowLong(hTextBuf, GWL_WNDPROC);
	SetWindowLong(hTextBuf, GWL_WNDPROC, (LONG)NewTextBufProc);
}


//
//	EWinConsole::DestroyConsoleWindow()
//
void EWinConsole::DestroyConsoleWindow(void)
{
	VERIFY( DestroyWindow(hTextBuf)	);
	VERIFY( DestroyWindow(hCmdLine)	);
	VERIFY( DestroyWindow(hConWnd)	);
	VERIFY( UnregisterClass(CONSOLE_CLASSNAME, GetModuleHandle(NULL)) );
}


/*-----------------------------------------------------------------------------
	WNDPROCs
-----------------------------------------------------------------------------*/
UINT_PTR	timer;
//
//	EWinConsole::ConWndProc()
//
LRESULT CALLBACK EWinConsole::ConWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
	HDC hDC;
	switch( uMsg )
	{ 
	case WM_TIMER :
				for (uint i=0; i<console_push.size(); i++)
				{
					const char *text = console_push[i].c_str();
					SendMessage(hTextBuf, EM_SETSEL, (WPARAM)(65536), (LPARAM)(65536));
					SendMessage(hTextBuf, EM_REPLACESEL, (WPARAM)0, (LPARAM)text);
				}
				console_push.clear();
			break;
    case WM_CTLCOLORSCROLLBAR:
	case WM_CTLCOLOREDIT :	
	case WM_CTLCOLORBTN :	
    case WM_CTLCOLORSTATIC :
				// change colors BG/FG for edits...
				hDC = (HDC)wParam;
				SetBkColor(hDC, SYSCON_BACKGROUND);
				SetTextColor(hDC, SYSCON_TEXTCOLOR);
				return (LRESULT)CreateSolidBrush(SYSCON_BACKGROUND);
			break;
    case WM_CREATE :	 
				timer = SetTimer(hWnd, 27, 5, NULL);
				
			break;
    case WM_CLOSE :	 
			PostQuitMessage(0);
			return 0;	// <-- disable Alt+F4 for con window
			break;
    case WM_DESTROY :
			break;
	case WM_ACTIVATE:
			SetFocus(hCmdLine);
			return 0;
			break;
    case WM_KEYDOWN :
			if (waiting) {
				waiting	=	false;
				key		=	(char)wParam;
			}
		break;
	default :	return DefWindowProc( hWnd, uMsg, wParam, lParam ) ;
	} 
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}


//
//	NewEditProc()
//
LRESULT CALLBACK EWinConsole::NewCmdLineProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
	static	bool	printable	= false;
	char text[256] = "";
	
	switch( uMsg )
	{ 
    case WM_CHAR :
		if (wParam==VK_RETURN)
		{		
			GetWindowText(hWnd, text, 255);
			if (input_handler) SetWindowText( hWnd,	input_handler->ExecuteCommand(text) );

			SendMessage(hWnd, EM_SETSEL, (WPARAM)(65536), (LPARAM)(65536));
			return 0;
		}  
		if (wParam==VK_TAB)
		{
			GetWindowText(hWnd, text, 255);
			if (input_handler) SetWindowText( hWnd,	input_handler->CompleteCommand(text) );
			
			SendMessage(hWnd, EM_SETSEL, (WPARAM)(65536), (LPARAM)(65536));
			return 0;
		}
		break;
		
    case WM_KEYDOWN :
		if (waiting)	waiting	=	false;
		
		if (wParam==VK_UP)
		{
			GetWindowText(hWnd, text, 255);
			if (input_handler) SetWindowText( hWnd,	input_handler->PrevCommand() );
			
			SendMessage(hWnd, EM_SETSEL, (WPARAM)(65536), (LPARAM)(65536));
			return 0;
		}

		if (wParam==VK_DOWN)
		{
			GetWindowText(hWnd, text, 255);
			if (input_handler) SetWindowText( hWnd,	input_handler->PrevCommand() );
			
			SendMessage(hWnd, EM_SETSEL, (WPARAM)(65536), (LPARAM)(65536));
			return 0;
		}
		break;
		
	default :	return OldCmdLineProc( hWnd, uMsg, wParam, lParam ) ;
	} 
	return OldCmdLineProc(hWnd,uMsg,wParam,lParam);
}


//
//	NewEditProc()
//
LRESULT CALLBACK EWinConsole::NewTextBufProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
	switch( uMsg )
	{ 
    case WM_KEYDOWN :
			if (waiting)	waiting	=	false;
		break;
		
	default :	return OldTextBufProc( hWnd, uMsg, wParam, lParam ) ;
	} 
	return OldTextBufProc(hWnd,uMsg,wParam,lParam);
}







	